<template>
  <div class="permission">
    <el-card class="mycard">
      <el-table
        :data="tableData"
        style="width: 100%"
        row-key="id"
        border
        class="mytable"
      >
        <el-table-column prop="name" label="名称" width="310">
        </el-table-column>
        <el-table-column prop="code" label="标识" width="310">
        </el-table-column>
        <el-table-column prop="description" label="描述" width="310">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{ row }">
            <el-button type="text" v-if="row.type === 1" @click="addPer(row.id)"
              >添加</el-button
            >
            <el-button type="text" @click="edit(row.id)">编辑</el-button>
            <el-button type="text" @click="del(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <template>
      <handledialog
        :showDialog.sync="showDialog"
        :headTitle="headTitle"
        :userId="userId"
        ref="handledialog"
        @upload="getAllPermission"
      ></handledialog>
    </template>
  </div>
</template>

<script>
import handledialog from './componets/dialog.vue'
import { getAllPermissionApi, delSysPermissionApi } from '../../api/permission'
export default {
  components: {
    handledialog
  },
  data () {
    return {
      tableData: [],
      userId: null,
      showDialog: false,
      headTitle: ''
    }
  },
  created () {
    this.getAllPermission()
  },
  methods: {
    // 添加
    addPer (id) {
      this.headTitle = '新增权限'
      this.showDialog = true
      this.userId = id
    },
    // 编辑
    edit (id) {
      this.headTitle = '编辑权限'
      this.showDialog = true
      this.userId = id
      this.$refs.handledialog.getSysPermission(id)
    },
    // 删除
    async del (id) {
      try {
        await this.$confirm('确定要删除该权限吗?', {
          type: 'warning'
        })
        await delSysPermissionApi(id)
        this.$message('删除成功')
        this.getAllPermission()
      } catch {
        return
      }
    },
    async getAllPermission () {
      const res = await getAllPermissionApi()
      this.tableData = this.turnData(res, '0')
      console.log(this.tableData)
    },
    turnData (arr, str) {
      return arr.filter(item => {
        if (item.pid === str) {
          item.children = this.turnData(arr, item.id)
          return true
        }
        return false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.permission {
  padding: 20px;
}
</style>
